/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.workforce.common.tags;

import java.lang.reflect.Method;
import java.util.List;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;

/**
 *
 * @author neo
 */
public class FieldListDBTag extends FieldBaseTag {

    protected String selected;
    protected String label;
    protected String value;
    protected String sql;

    @Override
    public int doStartTag() throws JspException {
        try {
            JspWriter out = pageContext.getOut();
            String mode = pageContext.getRequest().getParameter("mode");
            mode = (mode == null) ? "ins" : mode;
            StringBuffer s = new StringBuffer();
            s.append("<select ");
            if (id != null) {
                s.append("id=\"").append(id).append("\" ");
            }
            if (name != null) {
                s.append("name=\"").append(name).append("\" ");
            }
            if (style != null) {
                s.append("class=\"").append(style).append("\" ");
            }
            s.append(">\n");
            selected = (selected == null) ? "" : selected;
            
            List list = (List) pageContext.getAttribute(beanName);
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    Object obj = list.get(i);

                    Class cls = obj.getClass();
                    Method method = cls.getMethod("get" + value.substring(0, 1).toUpperCase() + value.substring(1), String.class);
                    String val = (String) method.invoke(obj, new Object[0]);
                    method = cls.getMethod("get" + label.substring(0, 1).toUpperCase() + label.substring(1), String.class);
                    String slabel = (String) method.invoke(obj, new Object[0]);
                    if (selected.equals(val)) {
                        s.append("<option value=\"").append(val).append("\" selected>").append(slabel).append("</option>\n");
                    } else {
                        s.append("<option value=\"").append(val).append("\">").append(slabel).append("</option>\n");
                    }
                }
            }
            s.append("</select>");
            out.print(s.toString());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return SKIP_BODY;
    }
}

